<!--  -->
<template>
  <!-- 课程管理 -->
  <div class='app-container'>
    <el-col :span="24" :xs="24">
      <el-form :model="tableParams" ref="queryForm" size="small" :inline="true" v-show="true" label-width="100px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="tableParams.courseName" placeholder="请输入课程名称" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="课程状态">
          <el-select v-model="tableParams.courseStatus">
            <el-option v-for="item in statusOptions" :key="item.value" :value="item.value"
              :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程分类" prop="courseType">
          <el-cascader v-model="courseTypeValue"
            :props="{ children: 'list', value: 'id', label: 'name', checkStrictly: true }"
            :options="options"></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['system:user:add']">新增</el-button>
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
      </el-row>
      <my-table :loading="loading" :tableData="tableData" paging :params="tableParams" :total="total">
        <el-table-column prop="courseImages" label="课程图片" align="center">
          <template slot-scope="scope">
            <viewer :images="[scope.row.courseImages]">
              <img v-for="item in [scope.row.courseImages]" :src="item" :key="item" alt="课程图片"
                style="width: 100px; height: 60px;">
            </viewer>
          </template>
        </el-table-column>
        <el-table-column prop="courseName" label="课程名称" align="center"></el-table-column>
        <el-table-column prop="courseTypeName" label="课程分类" align="center"></el-table-column>
        <el-table-column prop="courseLabels" label="课程标签" align="center" width="200">
          <template slot-scope="scope">
            <el-tag v-for="(item, index) in scope.row.courseLabelsName.split(',')" :key="index" type="success"
              style="margin-right: 10px;">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="courseStatus" label="课程状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.courseStatus == 0" type="success">待审核</el-tag>
            <el-tag v-else-if="scope.row.courseStatus == 1" type="danger">未通过</el-tag>
            <el-tag v-else-if="scope.row.courseStatus == 2" type="warning">未上架</el-tag>
            <el-tag v-else-if="scope.row.courseStatus == 3" type="info">已上架</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="courseIntroduction" label="课程简介" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="courseTime" label="课程时长" align="center">
          <template slot-scope="scope">
            {{ getTime(scope.row.courseTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="courseUrl" label="课程视频" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.type==0" type="text" size="mini"
              @click="videoDialog = true; currentVideoUrl = scope.row.courseUrl">预览</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope.row)"
              v-hasPermi="['system:user:edit']">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)"
              v-hasPermi="['system:user:remove']">删除</el-button>
            <el-button type="text" size="mini" @click="courseComment(scope.row)"
              v-hasPermi="['system:user:remove']">课程评论</el-button>
            <el-button type="text" size="mini" @click="courseRate(scope.row)"
              v-hasPermi="['system:user:remove']">课程评价</el-button>
          </template>
        </el-table-column>
      </my-table>
    </el-col>
    <!-- 课程弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="50%" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" size="small" label-width="120px">
        <el-form-item label="课程类型" prop="type">
          <el-radio-group v-model="dialogForm.type">
            <el-radio :label="0">视频</el-radio>
            <el-radio :label="1">文档</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="dialogForm.courseName" maxlength="20" placeholder="请输入课程名称" clearable />
        </el-form-item>
        <el-form-item label="课程图片" prop="courseImages">
          <imageUpload v-model="dialogForm.courseImages" :limit="1" :value="dialogForm.courseImages"></imageUpload>
        </el-form-item>
        <el-form-item label="课程分类" prop="courseType">
          <el-cascader v-model="dialogForm.courseType"
            :props="{ children: 'list', value: 'code', label: 'name', checkStrictly: true }"
            :options="options"></el-cascader>
        </el-form-item>
        <el-form-item label="课程标签" prop="courseLabels">
          <el-select multiple v-model="dialogForm.courseLabels">
            <el-option v-for="dict in dict.type.bus_course_lable" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态" prop="courseStatus">
          <el-select v-model="dialogForm.courseStatus">
            <el-option v-for="item in statusOptions" :key="item.value" :value="item.value"
              :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程简介" prop="courseIntroduction">
          <el-input v-model="dialogForm.courseIntroduction" type="textarea" :rows="3" placeholder="请输入课程简介" clearable />
        </el-form-item>
        <template v-if="dialogForm.type==0">
          <el-form-item label="视频类型" prop="urlType">
          <el-radio-group v-model="dialogForm.urlType">
            <el-radio :label="0">本地上传</el-radio>
            <el-radio :label="1">第三方链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="dialogForm.urlType == 1" label="视频地址" prop="courseUrl">
          <el-input v-model="dialogForm.courseUrl" placeholder="请输入视频地址" clearable />
        </el-form-item>
        <template v-else>
          <el-form-item label="上传视频">
            <fileUpload v-model="dialogForm.courseUrl" :limit="1" :fileSize="2048" @fileUploadSuccess="fileUploadSuccess"
              :fileType="['avi', 'wmv', 'mpg', 'mpeg', 'mov', 'rm', 'ram', 'swf', 'flv', 'mp4']"
              :value="dialogForm.courseUrl">
            </fileUpload>
          </el-form-item>
          <el-form-item label="课程时长(秒)" prop="courseTime">
            <!-- <el-input-number v-model="dialogForm.courseTime" controls-position="right" :min="1"
            :max="Infinity"></el-input-number> -->
            <el-input type="number" disabled v-model="dialogForm.courseTime" placeholder="上传视频后自动获取课程时长"></el-input>
          </el-form-item>
        </template>
        </template>
        <template v-else>
          <el-form-item label="文本内容">
            <editor v-model="dialogForm.courseContent" :min-height="192"/>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button type="primary" @click="save">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 预览课程视频 -->
    <el-dialog :visible.sync="videoDialog" width="50%" destroy-on-close>
      <video width="100%" controls :src="currentVideoUrl"></video>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { getCourseTypeList } from '@/api/courseManage/courseType';
import { getCourseList, addCourse, updateCourse, deleteCourse } from '@/api/courseManage/courseManage';
import { getTreeIds } from '@/utils/utils';
export default {
  dicts: ['bus_course_lable'],
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      statusOptions: [{
        value: 0,
        label: '待审核'
      }, {
        value: 1,
        label: '未通过'
      }, {
        value: 2,
        label: '未上架'
      }, {
        value: 3,
        label: '已上架'
      }],
      options: [],// 课程分类
      courseTypeValue: [],// 课程分类选中的值
      tableParams: {
        courseName: "",
        courseStatus: "",
        courseType: "",
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      tableData: [],
      total: 0,
      dialogFormVisible: false,
      dialogTitle: "添加课程",
      dialogForm: {
        type:0, //课程类型：0=视频课程，1=文本课程
        courseName: "", //课程名称
        courseType: [], //课程分类
        courseLabels: [],// 课程标签
        courseStatus: "", //课程状态
        courseIntroduction: "", //课程介绍
        courseTime: "", //课程时长
        urlType: 0, //视频类型  0上传视频 1第三方链接
        courseUrl: "", //视频地址
        courseImages: "", //课程图片
        courseContent:"",// 文本内容
      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        courseType: [
          { required: true, message: '请选择课程分类', trigger: 'change' }
        ],
        courseLabels: [
          { required: true, message: '请选择课程标签', trigger: 'change' }
        ],
        courseStatus: [
          { required: true, message: '请选择课程状态', trigger: 'change' }
        ],
        courseIntroduction: [
          { required: true, message: '请输入课程简介', trigger: 'blur' }
        ],
        courseTime: [
          { required: true, message: '请选择课程时长', trigger: 'change' }
        ],
        courseUrl: [
          { required: true, message: '请输入视频地址', trigger: 'blur' }
        ],
        courseImages: [
          { required: true, message: '请上传课程图片', trigger: 'change' }
        ],
      },
      videoDialog: false,
      currentVideoUrl: "",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getTime(time) {
      if (Number.isNaN(parseInt(time))) return '';
      // 转换为式分秒
      let h = parseInt((time / 60 / 60) % 24);
      h = h < 10 ? "0" + h : h;
      let m = parseInt((time / 60) % 60);
      m = m < 10 ? "0" + m : m;
      let s = parseInt(time % 60);
      s = s < 10 ? "0" + s : s;
      // 作为返回值返回
      return h + ":" + m + ":" + s;
    },
    // 获取课程分类选项
    getCourseTypeOptions() {
      getCourseTypeList().then(res => {
        if (res.code == 200) {
          this.options = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 获取课程列表数据
    getList() {
      this.loading = true
      this.tableParams.courseType = this.courseTypeValue.length > 0 ? this.courseTypeValue[this.courseTypeValue.length - 1] : "";
      getCourseList(this.tableParams).then(res => {
        this.loading = false
        if (res.code == 200) {
          this.tableData = res.rows;
          this.total = res.total
        }
      }).catch(err => {
        this.loading = false
      })
    },
    // 重置
    resetQuery() {
      this.tableData = [];
      this.courseTypeValue = [];
      this.total = 0;
      this.tableParams = {
        courseName: "",
        courseStatus: "",
        courseType: "",
        pageNum: 1,
        pageSize: 10
      }
      this.getList();
    },
    //添加
    handleAdd() {
      this.dialogFormVisible = true;
      this.dialogTitle = "添加课程";
      this.dialogForm = {
        type:0,
        courseName: "", //课程名称
        courseType: [], //课程分类
        courseLabels: [],// 课程标签
        courseStatus: "", //课程状态
        courseIntroduction: "", //课程介绍
        courseTime: "", //课程时长
        urlType: 0, //视频类型  0上传视频 1第三方链接
        courseUrl: "", //视频地址
        courseImages: "", //课程图片
        courseContent:"",
      };
      this.$nextTick(() => {
        this.$refs['dialogForm'].clearValidate();
      })

    },
    //编辑
    handleEdit(row) {
      console.log(row);
      this.dialogFormVisible = true;
      this.dialogTitle = "编辑课程";
      let courseLabels = row.courseLabels.split(',');
      let pid = getTreeIds(this.options, row.courseType, { children: 'list', id: 'code' })['ids'];
      this.$nextTick(() => {
        this.dialogForm = {
          type:row.type,
          courseName: row.courseName, //课程名称
          courseType: pid, //课程分类
          courseLabels: courseLabels,// 课程标签
          courseStatus: row.courseStatus, //课程状态
          courseIntroduction: row.courseIntroduction, //课程介绍
          courseTime: row.courseTime, //课程时长
          urlType: row.urlType, //视频类型  0上传视频 1第三方链接
          videoCover: row.videoCover, //视频封面
          courseUrl: row.courseUrl, //视频地址
          courseImages: row.courseImages, //课程图片
          courseId: row.courseId,
          courseContent:row.courseContent,
        };
        this.$refs['dialogForm'].clearValidate();
      })
    },
    // 视频上传成功 获取视频时长
    fileUploadSuccess(file) {
      console.log(file);
      var url = URL.createObjectURL(file.raw);
      var audioElement = new Audio(url);
      var self = this;
      var result;
      audioElement.addEventListener("loadedmetadata", function () {
        // 视频时长值的获取要等到这个匿名函数执行完毕才产生
        result = audioElement.duration; //得到时长为秒
        self.dialogForm.courseTime = parseInt(result); //转为int值
      });
    },
    //删除
    handleDelete(row) {
      this.$confirm('是否确认删除该课程?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCourse(row.courseId).then(res => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.getList();
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 保存
    save() {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          this.submiting = true;
          let params = {
            type: this.dialogForm.type,
            courseName: this.dialogForm.courseName,
            courseType: this.dialogForm.courseType.length > 0 ? this.dialogForm.courseType[this.dialogForm.courseType.length - 1] : '',
            courseLabels: this.dialogForm.courseLabels.length > 0 ? this.dialogForm.courseLabels.join(',') : '',
            courseStatus: this.dialogForm.courseStatus,
            courseIntroduction: this.dialogForm.courseIntroduction,
            courseTime: this.dialogForm.courseTime,
            urlType: this.dialogForm.urlType,
            courseUrl: this.dialogForm.courseUrl,
            courseImages: this.dialogForm.courseImages,
            courseId: this.dialogForm.courseId ? this.dialogForm.courseId : '',
            courseContent:this.dialogForm.courseContent,
          }
          if (this.dialogForm.type == 0 && this.dialogForm.courseUrl == "") {
            this.$message.warning("请上传视频");
            return false;
          }
          if (this.dialogTitle == '添加课程') {
            addCourse(params).then(res => {
              this.submiting = false;
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            updateCourse(params).then(res => {
              this.submiting = false;
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 课程评论
    courseComment(row) {
      this.$router.push({
        path: '/course/commentList',
        query: {
          courseId: row.courseId
        }
      })
    },
    // 课程评价
    courseRate(row) {
      this.$router.push({
        path: '/course/rateList',
        query: {
          courseId: row.courseId
        }
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getCourseTypeOptions();
    this.getList();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
}
</script>
<style scoped></style>
